import Koa from 'koa';
import fs from 'fs-extra';
import Router from 'koa-router';
import { errLog } from '../log';
import { IDirInfo, IFileDetail } from '../../type';

import {
    getRandom,
    packageRouter,
    travelSortFile,
    packageResponse,
    fixPathSeparator,
    readDirInnerFiles,
    writeFileByStream,
    filenameAppendChar,
    readDirInnerFilesToObject,
    travelReadDirInnerAllFiles,
} from '../util';

function useRouter(router: Router, app: Koa): void {
    // ...
    const route = packageRouter(router, app);

    /**
     * 查询文件详情
     */
    route('post', '/getFileDetail', ({ response }, body) => {
        try {
            const { filepath } = body;
            if (fs.existsSync(filepath) && fs.statSync(filepath).isFile()) {
                const detail: IFileDetail = {
                    filepath,
                    filename: filepath.split(/\/|\\/).pop(),
                    content: fs.readFileSync(filepath, 'utf-8'),
                };
                packageResponse(response, detail);
            } else {
                packageResponse(response, null, 1, 200, '非文件路径');
            }

            // ...
        } catch (error) {
            errLog(error);
            packageResponse(response, null, 0, 500, JSON.stringify(error));
        }
    });

    /**
     * 查询目录下的所有资源信息
     */
    route('post', '/getDirInnerAllFiles', ({ response }, body) => {
        try {
            const { dirpath } = body;

            const result: IDirInfo = {
                innerDirs: [],
                innerAllFiles: [],
            };
            travelReadDirInnerAllFiles(dirpath, result.innerAllFiles, result.innerDirs);
            travelSortFile(result.innerDirs);
            packageResponse(response, result);

            // ...
        } catch (error) {
            errLog(error);
            packageResponse(response, null, 0, 500, JSON.stringify(error));
        }
    });

    /**
     * 查询目录下的一级资源信息
     */
    route('post', '/getDirInnerFiles', ({ response }, body) => {
        try {
            const { dirpath, isDeep } = body;

            const result = readDirInnerFiles(dirpath, isDeep);
            packageResponse(response, result);

            // ...
        } catch (error) {
            errLog(error);
            packageResponse(response, null, 0, 500, JSON.stringify(error));
        }
    });

    /**
     * 创建目录
     */
    route('post', '/createFolder', ({ response }, body) => {
        try {
            const { dirpath } = body;

            const dirExist = fs.existsSync(dirpath);
            if (dirExist) {
                packageResponse(response, null, 1, 200, '目录已存在');
            } else {
                fs.mkdirsSync(dirpath);
                packageResponse(response);
            }

            // ...
        } catch (error) {
            errLog(error);
            packageResponse(response, null, 0, 500, JSON.stringify(error));
        }
    });

    /**
     * 转移目录
     */
    route('post', '/transferFolder', ({ response }, body) => {
        try {
            let { from, to, overwrite = false } = body;
            from = fixPathSeparator(from);
            to = fixPathSeparator(to);

            const a = to.split('/');
            a.pop();
            const saveTo = a.join('/');

            if (fs.statSync(from).isDirectory() && fs.statSync(saveTo).isDirectory()) {
                if (overwrite) {
                    fs.moveSync(from, to, { overwrite: true });
                    packageResponse(response);
                } else {
                    const dirExist = fs.existsSync(to);
                    if (dirExist) {
                        packageResponse(response, null, 1, 200, '需要转移的目录已在目标地址');
                    } else {
                        fs.moveSync(from, to);
                        packageResponse(response);
                    }
                }
            } else {
                packageResponse(response, null, 1, 200, '源地址或目标地址不是目录');
            }

            // ...
        } catch (error) {
            errLog(error);
            packageResponse(response, null, 0, 500, JSON.stringify(error));
        }
    });

    /**
     * 删除目录
     */
    route('post', '/deleteFolder', ({ response }, body) => {
        try {
            const { dirpaths } = body;

            for (let i = 0; i < dirpaths.length; i++) {
                const dirpath = fixPathSeparator(dirpaths[i]);
                const dirExist = fs.existsSync(dirpath);
                if (dirExist) {
                    fs.removeSync(dirpath);
                }
            }

            packageResponse(response);

            // ...
        } catch (error) {
            errLog(error);
            packageResponse(response, null, 0, 500, JSON.stringify(error));
        }
    });

    /**
     * 转移文件
     */
    route('post', '/transferFile', async ({ response }, body) => {
        try {
            let { list, overwrite = false } = body;

            list = list || [];

            for (let i = 0; i < list.length; i++) {
                let { from, to } = list[i];
                from = fixPathSeparator(from);
                to = fixPathSeparator(to);

                const fromStat = fs.statSync(from);
                const toStat = fs.statSync(to);

                const toIsDirectory = toStat.isDirectory();
                const fromIsFile = fromStat.isFile();
                const toIsFile = toStat.isFile();

                if (fromIsFile) {
                    if (toIsDirectory) {
                        if (overwrite) {
                            const toFilePath = to + '/' + from.split('/').pop();
                            await writeFileByStream(from, toFilePath);
                            fs.removeSync(from);
                        } else {
                            const toFilePath = to + '/' + from.split('/').pop();
                            if (fs.existsSync(toFilePath)) {
                                await writeFileByStream(from, filenameAppendChar(toFilePath, '_' + getRandom(5)));
                                fs.removeSync(from);
                            } else {
                                await writeFileByStream(from, toFilePath);
                                fs.removeSync(from);
                            }
                        }
                    } else if (toIsFile) {
                        if (overwrite) {
                            fs.moveSync(from, to, { overwrite: true });
                        } else {
                            await writeFileByStream(from, filenameAppendChar(to, '_' + getRandom(5)));
                            fs.removeSync(from);
                        }
                    }
                }
            }

            packageResponse(response);

            // ...
        } catch (error) {
            errLog(error);
            packageResponse(response, null, 0, 500, JSON.stringify(error));
        }
    });

    /**
     * 删除文件
     */
    route('post', '/deleteFile', ({ response }, body) => {
        try {
            const { filepaths } = body;

            for (let i = 0; i < filepaths.length; i++) {
                const filepath = fixPathSeparator(filepaths[i]);
                const dirExist = fs.existsSync(filepath);
                if (dirExist) {
                    fs.removeSync(filepath);
                }
            }

            packageResponse(response);

            // ...
        } catch (error) {
            errLog(error);
            packageResponse(response, null, 0, 500, JSON.stringify(error));
        }
    });

    /**
     * 重命名文件或者目录
     */
    route('post', '/renameFileOrFolder', ({ response }, body) => {
        try {
            let { oldpath, newpath } = body;
            oldpath = fixPathSeparator(oldpath);
            newpath = fixPathSeparator(newpath);

            const oldExist = fs.existsSync(oldpath);
            const newExist = fs.existsSync(newpath);

            if (oldExist && !newExist) {
                fs.renameSync(oldpath, newpath);
                packageResponse(response);
            } else {
                packageResponse(response, null, 1, 200, '旧资源不存在或者新资源已存在');
            }

            // ...
        } catch (error) {
            errLog(error);
            packageResponse(response, null, 0, 500, JSON.stringify(error));
        }
    });

    /**
     * 拷贝文件或目录
     */
    route('post', '/copyFileOrFolder', async ({ response }, body) => {
        try {
            let { list, overwrite = false } = body;
            list = list || [];

            for (let i = 0; i < list.length; i++) {
                let { from, to } = list[i];
                from = fixPathSeparator(from);
                to = fixPathSeparator(to);

                if (!fs.existsSync(from) || !fs.existsSync(to)) {
                    continue;
                }

                const fromStat = fs.statSync(from);
                const toStat = fs.statSync(to);

                const fromIsDirectory = fromStat.isDirectory();
                const toIsDirectory = toStat.isDirectory();
                const fromIsFile = fromStat.isFile();

                if (toIsDirectory) {
                    if (fromIsFile) {
                        const toFilePath = to + '/' + from.split('/').pop();
                        if (overwrite) {
                            await writeFileByStream(from, toFilePath);
                        } else {
                            if (fs.existsSync(toFilePath)) {
                                await writeFileByStream(from, filenameAppendChar(toFilePath, '_' + getRandom(5)));
                            } else {
                                await writeFileByStream(from, toFilePath);
                            }
                        }
                    } else if (fromIsDirectory) {
                        const toDirPath = to + '/' + from.split('/').pop();
                        if (overwrite) {
                            if (fs.existsSync(toDirPath)) {
                                fs.removeSync(toDirPath);
                            }
                            fs.mkdirsSync(toDirPath);
                            fs.copySync(from, toDirPath);
                        } else {
                            if (fs.existsSync(toDirPath)) {
                                fs.mkdirsSync(toDirPath);
                                fs.copySync(from, filenameAppendChar(toDirPath, '_' + getRandom(5)));
                            } else {
                                fs.mkdirsSync(toDirPath);
                                fs.copySync(from, toDirPath);
                            }
                        }
                    }
                }
            }

            packageResponse(response);

            // ...
        } catch (error) {
            errLog(error);
            packageResponse(response, null, 0, 500, JSON.stringify(error));
        }
    });

    /**
     * 读取目录内部文件，按对象格式输出
     */
    route('post', '/readDirInnerFilesToObject', async ({ response }, body) => {
        try {
            const { dirpath } = body;
            if (fs.statSync(dirpath).isDirectory()) {
                const result = {};
                readDirInnerFilesToObject(dirpath, result);
                packageResponse(response, result);
            } else {
                throw new Error('传入参数不是一个目录路径');
            }
        } catch (error) {
            errLog(error);
            packageResponse(response, null, 0, 500, JSON.stringify(error));
        }
    });
}

export default useRouter;
